﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace TCPServer
{
    public class ClienteAceptadoEventArgs : EventArgs
    {
        public readonly TcpClient cliente;

        public ClienteAceptadoEventArgs (TcpClient cliente)
        {
            this.cliente = cliente;
        }
    }

    public delegate void ClienteAceptado (object sender, ClienteAceptadoEventArgs evargs);
    
    public class Servidor
    {
        TcpListener _listener       = null;
        Thread      _listenThread   = null;

        public event ClienteAceptado clienteAceptado;

        public Servidor ()
        {
            //
        }

        void flisten ()
        {
            _listener.Start();
            
            for (; ; )
            {
                TcpClient cliente = _listener.AcceptTcpClient ();
                
                if (clienteAceptado != null)
                    clienteAceptado (this, new ClienteAceptadoEventArgs (cliente));
            }
        }

        public void iniciar (int puerto)
        {
            _listener       = new TcpListener (IPAddress.Any, puerto);
            _listenThread   = new Thread (new ThreadStart(flisten));
            _listenThread.IsBackground = true;
            _listenThread.Start ();
        }

        public void parar ()
        {
            _listener.Stop ();
        }
    }
}
